/**
 * Description:
 * User: Vijay <1937832819@qq.com>
 * Date: 2020/08/19
 * Time: 10:57
 */

package models

import (
	"time"

	"github.com/astaxie/beego/validation"
)

type Category struct {
	Id          int       `gorm:"primaryKey" json:"id" form:"id"`
	Slug        string    `json:"slug" form:"slug"`
	Name        string    `valid:"Required;" json:"name"  form:"name"` // Name 不能为空
	Keywords    string    `json:"keywords" form:"keywords"`
	Description string    `json:"description" form:"description"`
	Status      int       `gorm:"default:1" json:"status" form:"status"`
	Sort        int       `json:"sort" form:"sort"`
	Pid         int       `json:"pid" form:"pid"`
	CreatedAt   time.Time `json:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt" form:"updatedAt"`
	DeletedAt   time.Time `json:"deletedAt"`
	// DeletedAt   gorm.DeletedAt `gorm:"index"` 关闭软删除
}

func (a *Category) TableName() string {
	return TableName("categories")
}

// 自定义验证规则
func (m *Category) SelfValid() (msg interface{}) {
	var model Category
	valid := validation.Validation{}
	info := map[string]interface{}{}
	if b, _ := valid.Valid(m); !b {
		for _, err := range valid.Errors {
			return err.Message
		}
	}
	if m.Id != 0 {
		Db.Model(&model).Where("name = ?", m.Name).Where("id <> ?", m.Id).Find(&info)
	} else {
		Db.Model(&model).Where("name = ?", m.Name).Find(&info)
	}
	// Name 唯一
	if len(info) > 0 {
		return "名称唯一，不能重复"
	}
	return nil
}
